package com.gjs.common.pojo.dto.response;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.TypeUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@NoArgsConstructor
@ApiModel("列表分页对象")
public class ListPageRsp<T> {
    @ApiModelProperty("总条目数")
    private long total;
    @ApiModelProperty("每页条目数")
    private long size;
    @ApiModelProperty("页码")
    private long page;
    @ApiModelProperty("列表数据")
    private List<?> records;
    @JsonIgnore
    private Class<T> target;

    ListPageRsp(Class<T> target) {
        this.target = target;
    }

    public ListPageRsp<T> build(IPage<?> page) {
        this.total = page.getTotal();
        this.size = page.getSize();
        this.page = page.getPages();

        this.records = target == null ? page.getRecords() : page.convert(row -> BeanUtil.copyProperties(row, target)).getRecords();

        return this;
    }

    public static <T> ListPageRsp<T> of(IPage<?> page) {
        return new ListPageRsp<T>().build(page);
    }

    public static <T> ListPageRsp<T> of(IPage<?> page, Class<T> target) {
        return new ListPageRsp<>(target).build(page);
    }
}
